package com.bilin.coin.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bilin.coin.ApiConstant;
import com.bilin.coin.MainActivity;
import com.bilin.coin.R;
import com.bilin.coin.bean.BiLinWallet;
import com.bilin.coin.bean.CommonBean;
import com.bilin.coin.bean.CommonSuccessEvent;
import com.bilin.coin.bean.UserInfo;
import com.bilin.coin.common.base.BaseAppCompatActivity;
import com.bilin.coin.common.base.BaseFragment;
import com.bilin.coin.network.RequestUtils;
import com.bilin.coin.network.callback.StringCallBack;
import com.bilin.coin.tools.AlertUtils;
import com.bilin.coin.tools.Geter;
import com.bilin.coin.utils.DialogUtils;
import com.bilin.coin.utils.GsonUtil;
import com.bilin.coin.utils.SharedPreferencesUtils;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import kt.com.bilin.coin.common.UserDataCache;

public class MyFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {


    @BindView(R.id.sw_refresh)
    SwipeRefreshLayout sw_refresh;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.ll_user)
    LinearLayout ll_user;
    @BindView(R.id.ll_login)
    LinearLayout ll_login;

    @BindView(R.id.tv_gold)
    TextView tv_gold;
    @BindView(R.id.tv_seed)
    TextView tv_seed;
    @BindView(R.id.tv_point)
    TextView tv_point;
    @BindView(R.id.tv_jx)
    TextView tv_jx;
    @BindView(R.id.tv_invite_code)
    TextView tv_invite_code;
    @BindView(R.id.tv_version)
    TextView tv_version;
    @BindView(R.id.tv_bl_num)
    TextView tv_bl_num;
    @BindView(R.id.tv_exit)
    TextView tv_exit;
    @BindView(R.id.tv_level)
    TextView tv_level;

    private boolean isLogin;

    private BiLinWallet biLinWallet;
    private String kycStatus = "0";

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        sw_refresh.setOnRefreshListener(this);
        getSession();
        getWallet();
        tv_version.setText(TextUtils.isEmpty(packageName(mContext, 0)) ? "当前版本V：1.0.1" : "当前版本V：" + packageName(mContext, 0));
     /*   fillDataFirst();

        getDataWaitPoint();
        getData();
        getIsOpenEnterOrder();*/
    }

    public String packageName(Context context, int type) {
        PackageManager manager = context.getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            if (type == 0) {
                name = info.versionName;
            } else {
                name = info.packageName;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }

    private void getWallet() {
        new Geter((BaseAppCompatActivity) mContext, false, true) {
            @Override
            protected String fillUrl() {
                return "/api/bl-wallet/getMoney";
            }

            @Override
            protected Map<String, String> fillParams() {
                return new HashMap<>();
            }

            @Override
            protected void disposeSuccess(String dataJson) {
                super.disposeSuccess(dataJson);
                biLinWallet = GsonUtil.GsonToBean(dataJson, BiLinWallet.class);
                fillWallet();
            }
        };
    }

    private void fillWallet() {
        tv_gold.setText(biLinWallet.getJd());
        tv_seed.setText(biLinWallet.getZz());
        tv_point.setText(biLinWallet.getGf());
        tv_jx.setText(biLinWallet.getJx());
        tv_bl_num.setText("拥有" + biLinWallet.getBlq() + "张比邻券");
        tv_level.setText("Lv " + biLinWallet.getLevel());
    }

    @OnClick({R.id.rl_coupon, R.id.tv_login, R.id.tv_register,
            R.id.rl_about_us, R.id.rl_feedback, R.id.rl_guide,
            R.id.ll_safe, R.id.ll_points,
            R.id.ll_jixiao, R.id.ll_seed, R.id.ll_gold_bean,
            R.id.ll_my_team, R.id.tv_exit, R.id.rl_invite,
            R.id.rl_real, R.id.ll_my_mill, R.id.ll_my_wallet})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_login) {
            baseStartActivity("/auction/LoginActivity");
            return;
        }
        if (id == R.id.tv_register) {
            baseStartActivity("/auction/RegisterActivity");
            return;
        }
        if (!isLogin) {
            baseStartActivity("/auction/LoginActivity");
            return;
        }
        switch (view.getId()) {
            case R.id.tv_exit:
                AlertUtils.dialog((Activity) mContext, "提示", "您确定退出登录？", new AlertUtils.OnPositiveClick() {
                    @Override
                    public void onClick() {
                        exit();
                    }
                });
                break;
            case R.id.rl_guide:
                jumpArticle("24", "新手指南");
                break;
            case R.id.rl_about_us:
                jumpArticle("18", "关于我们");
                break;
            case R.id.rl_feedback:
                baseStartActivity("/v2/user/feedback");
                //jumpArticle("17", "在线客服");
                break;
            case R.id.ll_my_wallet:
                showWaitDev();
                break;
            case R.id.ll_my_mill:
                ((MainActivity) mContext).selectTab(R.id.rb_mill);
                break;
            case R.id.rl_invite:
                toInvite();
                break;
            case R.id.rl_coupon:
                baseStartActivity("/auction/CouponActivity");
                break;
            case R.id.ll_safe:
                baseStartActivity("/safe/SafeActivity");
                break;
            case R.id.ll_points:
                baseStartActivity("/auction/PointDetailActivity");
                break;
            case R.id.ll_jixiao:
                baseStartActivity("/auction/JiXiaoDetailActivity");
                break;
            case R.id.ll_seed:
                baseStartActivity("/auction/SeedDetailActivity");
                break;
            case R.id.ll_gold_bean:
                baseStartActivity("/auction/GoldBeanDetailActivity");
                break;
            case R.id.ll_my_team:
                baseStartActivity("/auction/MyTeamActivity");
                break;
            case R.id.rl_real:
                toReal();
                break;
        }
    }

    private void toInvite() {
        baseStartActivity("/auction/InviteActivity");
    }

    private void toReal() {
        //身份认证状态 0未认证 1审核中 2已认证 3认证失败
        switch (kycStatus) {
            case "0":
                baseStartActivity("/v2/safe/AuthActivity");
                break;
            case "1":
                showToast("审核中");
                break;
            case "2":
                showToast("已认证");
                break;
            case "3":
                baseStartActivity("/safe/AuthFailureActivity");
                break;
        }
    }

    private void showWaitDev() {
        AlertUtils.dialog((Activity) mContext, new AlertUtils.OnPositiveClick() {
            @Override
            public void onClick() {

            }
        });
    }

    private void fillDataFirst() {
        try {
            String userStr = SharedPreferencesUtils.getInstance().getString(ApiConstant.USERINFO_JSON, "");
            UserInfo userInfo = GsonUtil.GsonToBean(userStr, UserInfo.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void exit() {
        DialogUtils.showDialogLoading(mContext);
        RequestUtils
                .post()
                .url("/api/user/logout")
                .build()
                .compose(this.<String>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new StringCallBack<CommonBean>() {
                    @Override
                    public void onCallBackNext(CommonBean result) {
                        DialogUtils.dismissDialogLoading();
                        showToast(result.getMsg());
                        logoutSuccess();
                    }

                    @Override
                    public void onCallBackError(Throwable e) {
                        showMsg(e);
                        DialogUtils.dismissDialogLoading();
                    }
                });
    }

    @Override
    public void userInfoSession(UserInfo userInfo) {
        super.userInfoSession(userInfo);
        if (userInfo == null) return;


        fillData(userInfo);
    }

    private void fillData(UserInfo userInfo) {
        isLogin = userInfo.isLogin();
        kycStatus = userInfo.getKycStatus();
        //GlideUtils.getInstance().loadCircleImageLocal(mContext, R.mipmap.ic_launcher, iv_avatar);
        if (isLogin) {
            ll_user.setVisibility(View.VISIBLE);
            ll_login.setVisibility(View.GONE);
            tv_phone.setText(userInfo.getMobile());
            tv_exit.setVisibility(View.VISIBLE);
        } else {
            ll_user.setVisibility(View.GONE);
            ll_login.setVisibility(View.VISIBLE);
            tv_exit.setVisibility(View.GONE);
        }
        String id = userInfo.getInviteCode();
        tv_invite_code.setText("邀请码:" + (TextUtils.isEmpty(id) ? "" : id));
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my;
    }


    private void jumpWeb(String url) {
        baseStartActivityWith("/common/WebPageLoading")
                .withString("url", url)
                //.withString("url", /*ApiConstant.BaseUrl +*/ "https://qr.alipay.com/bax00853x1pephnygaki20fc")
                .withString("title", "详情")
                //.withInt("type", 1)
                .navigation();
    }


    /**
     * 登录成功
     *
     * @param commonSuccessEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccessEvent(CommonSuccessEvent commonSuccessEvent) {
        if (commonSuccessEvent.getType() == CommonSuccessEvent.LoginSuccess) {
            loginSuccess();
            getWallet();
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent);
    }

    /**
     * 退出成功
     *
     * @param commonSuccessEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void logoutSuccessEvent(CommonSuccessEvent commonSuccessEvent) {
        if (commonSuccessEvent.getType() == CommonSuccessEvent.LogoutSuccess) {
            logoutSuccess();
        }

        EventBus.getDefault().removeStickyEvent(commonSuccessEvent);
    }

    private void logoutSuccess() {
        isLogin = false;
        ll_login.setVisibility(View.VISIBLE);
        ll_user.setVisibility(View.GONE);
        tv_exit.setVisibility(View.GONE);
        tv_gold.setText("0");
        tv_seed.setText("0");
        tv_point.setText("0");
        tv_jx.setText("0");
        tv_invite_code.setText("邀请码:");
        tv_bl_num.setText("拥有0张比邻券");
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.CSRF_TOKEN, "");
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.LoginSmsToken, "");
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.Mobile, "");
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsHasSafeWord, "");
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsLogin, "");
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.USER_ID, "");
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.USERINFO_JSON, "");
        UserDataCache.INSTANCE.clear();
        //GlideUtils.getInstance().loadCircleImageLocal(mContext, R.mipmap.icon_head_portrait, iv_avatar);
    }

    private void loginSuccess() {
        getSession();
        //getData();
        //getDataWaitPoint();
        //tv_user_id.setText(loginSuccessEvent.getMsg());
        //tv_user_id.setText("ID：" + SharedPreferencesUtils.getInstance().getString(ApiConstant.USER_ID, ""));
        //showAvatar();
    }

    private void showAvatar() {
        String dataJson = SharedPreferencesUtils.getInstance().getString(ApiConstant.USERINFO_JSON, "");
        UserInfo userInfo = GsonUtil.GsonToBean(dataJson, UserInfo.class);

    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    /**
     * 认证成功
     *
     * @param commonSuccessEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void authSuccessEvent(CommonSuccessEvent commonSuccessEvent) {
        if (commonSuccessEvent.getType() == CommonSuccessEvent.AuthSuccess) {

            getSession();
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent);
    }

    /**
     * 头像更新成功
     *
     * @param commonSuccessEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void avatarSuccessEvent(CommonSuccessEvent commonSuccessEvent) {
        if (commonSuccessEvent.getType() == CommonSuccessEvent.UpdateAvatarSuccess) {
            showAvatar();
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent);
    }

    /**
     * 昵称更新成功
     *
     * @param commonSuccessEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void nickSuccessEvent(CommonSuccessEvent commonSuccessEvent) {
        if (commonSuccessEvent.getType() == CommonSuccessEvent.UpdateNickSuccess) {
            getSession();
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent);
    }

    /**
     * 去实名
     *
     * @param commonSuccessEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void goToReal(CommonSuccessEvent commonSuccessEvent) {
        if (commonSuccessEvent.getType() == CommonSuccessEvent.GOTOREAL) {
            toReal();
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent);
    }

    /**
     * 去邀请
     *
     * @param commonSuccessEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void goToInvite(CommonSuccessEvent commonSuccessEvent) {
        if (commonSuccessEvent.getType() == CommonSuccessEvent.GOTOINVITE) {
            toInvite();
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent);
    }


    @Override
    public void onRefresh() {
        getSession();
        getWallet();
        //getData();
        //getDataWaitPoint();
        sw_refresh.setRefreshing(false);
    }


}
